package qinggui.mlz.module.category.service;


import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import qinggui.mlz.module.category.entity.Category;
import qinggui.mlz.module.category.entity.dto.CategoryDTO;
import qinggui.mlz.module.rocketmq.event.CategoryDeleteEvent;
import qinggui.mlz.module.category.mapper.CategoryMapper;
import qinggui.mlz.module.star.mapper.StarMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 类目表 服务实现类
 * </p>
 *
 * @author 清规
 * @since 2025-02-15
 */
@Service
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private StarMapper starMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    public Integer insert(Category category) {
        return categoryMapper.insert(category);
    }

    public Integer update(Category category) {
        return categoryMapper.update(category);
    }

    public Integer delete(Long id, Integer timeStamp) {
        return categoryMapper.delete(id, timeStamp);
    }


    /**
     * 获取所有类目
     *
     * @return List<Category>
     */
    public List<Category> getAllParentCategory(String keyword) {
        return categoryMapper.getAllParentCategory(keyword);
    }

    /**
     * 获取类目详情
     *
     * @param id 主键id
     * @return Category
     */
    public Category getById(Long id) {
        if (id == null || id < 1) {
            throw new RuntimeException("id不合法或id不能为空");
        }
        return categoryMapper.getById(id);
    }


    /**
     * 新增或修改类目
     *
     * @param id            主键id
     * @param categoryName  类目名称
     * @param categoryImage 类目图片
     * @param parentId      父类目id
     * @return String
     */
    public String edit(Long id, String categoryName, String categoryImage, Long parentId) {
        if (id != null && id < 1) {
            throw new RuntimeException("id不合法");
        }
        if (parentId != null && parentId < 1) {
            throw new RuntimeException("parentId不合法");
        }
        if (categoryName == null || categoryImage == null) {
            throw new RuntimeException("参数不能为空");
        }
        if (Objects.equals(id, parentId)) {
            throw new RuntimeException("id和parentId不能相同");
        }
        Category category = new Category().setCategoryName(categoryName).setCategoryImage(categoryImage)
                .setUpdateTime((int) (System.currentTimeMillis() / 1000)).setParentId(parentId);

        if (id == null) {
            insert(category.setCreateTime((int) (System.currentTimeMillis() / 1000)).setIsDeleted(0));
            Long id1 = category.getId();
            if (id1 == null) {
                throw new RuntimeException("获取新增后的id失败");
            }
            return id1.toString();
        }
        Category byId = categoryMapper.getById(id);
        if (byId == null) {
            throw new RuntimeException("id不存在");
        }
        update(category.setId(id));
        return id.toString();
    }

    /**
     * 删除类目
     *
     * @param id 主键id
     * @return String
     */
    /* 事务属性配置分别为：
     *    1. 默认值，支持当前事务，不存在就新建
     *    2. 使用数据库默认隔离级别（Mysql读已提交）
     *    3. 所有异常都回滚（默认是运行时异常回滚）
     *    4. 默认30秒超时
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class, timeout = 30)
    public String delete(Long id) {
        if (id == null || id < 1) {
            throw new RuntimeException("id不合法或id不能为空");
        }
        int tampStamp = (int) (System.currentTimeMillis() / 1000);
        List<Long> deletesIds = new ArrayList<>();
        deletesIds.add(id);
        List<Category> subCategoriesByCategoryId = categoryMapper.getCategoryByParentId(id);
        for (Category category : subCategoriesByCategoryId) {
            deletesIds.add(category.getId());
        }
        // 批量删除对应的类目
        Integer deleteBatchCategory = categoryMapper.deleteInDeletes(deletesIds, tampStamp);
        // todo 将要删除的类目id，推送到消息队列中，后续删除对应类目id中的球星。
        CategoryDeleteEvent event = new CategoryDeleteEvent();
        event.setCategoryIds(deletesIds).setTampStamp(tampStamp).setOperator("qinggui");
        rocketMQTemplate.sendMessageInTransaction("category-delete-topic", MessageBuilder.withPayload(event).build(), deletesIds);
        return deleteBatchCategory > 0 ? "成功" : "失败";
    }

    /**
     * 获取所有分类树
     *
     * @return
     */
    public List<Category> getAllCategory() {
        return categoryMapper.getAllCategory();

    }

    /**
     * 获取所有子类目
     *
     * @param categoryId
     * @return
     */
    public List<CategoryDTO> getSubCategoriesByCategoryId(Long categoryId) {
        return categoryMapper.getSubCategoriesByCategoryId(categoryId);
    }

    public List<Category> getCategoryByParentId(Long parentId) {
        return categoryMapper.getCategoryByParentId(parentId);
    }
}
